package com.eliota.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eliota.common.Constants;
import com.eliota.common.R;
import com.eliota.entity.Dict;
import com.eliota.entity.Role;
import com.eliota.entity.User;
import com.eliota.service.DictService;
import com.eliota.service.RoleService;
import com.eliota.service.TypeService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author MG
 * @since 2023-03-28
 */
@RestController
@RequestMapping("/dict")
public class DictController {

    @Resource
    private DictService dictService;



    /**
     * 新增
     * @param dict
     * @return
     */
    @PostMapping("/save")
    public R save(@RequestBody Dict dict){
        dict.setType("icon");
        return R.success(dictService.saveOrUpdate(dict));
    }

    @GetMapping("/list")
    public R findAll(){
        return R.success(dictService.list());
    }

    @DeleteMapping("/{id}")
    public R delete(@PathVariable Integer id){
        boolean isDel = dictService.removeById(id);
        if(isDel){
            return R.success();
        }else {
            return R.error("删除失败");
        }
    }

    @PostMapping("/bath/del")
    public R deleteBath(@RequestBody List<Integer> ids){
        boolean b = dictService.removeBatchByIds(ids);
        if(b){
            return R.success(true,"删除成功");
        }else {
            return R.error("删除失败");
        }
    }

    @GetMapping("/page")
    public R findPage(@RequestParam Integer pageNum,
                      @RequestParam Integer pageSize,
                      @RequestParam String dictName){
        Page<Dict> rolePage = new Page<>(pageNum, pageSize);
        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper.like("name",dictName).orderByDesc("id");

        return R.success(dictService.page(rolePage,dictQueryWrapper));
    }

    @GetMapping("/icons")
    public R getIcons(){
        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper.eq("type", Constants.DICT_TYPE_ICON);
        return R.success(dictService.list(dictQueryWrapper));
    }

  /*  <el-table-column prop="id" label="ID"  show-overflow-tooltip/>
      <el-table-column prop="name" label="名称"  show-overflow-tooltip/>
      <el-table-column prop="value" label="字典值"  show-overflow-tooltip/>
      <el-table-column prop="type" label="类型" width="150"/>*/


    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<Dict> list = dictService.list();
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("id", "id");
        writer.addHeaderAlias("name", "图标名");
        writer.addHeaderAlias("value", "字典值");
        writer.addHeaderAlias("nickname", "昵称");
        writer.addHeaderAlias("type", "类型");
        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);
        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();

    }

    /**
     * excel
     * @param file
     * @throws Exception
     */
    @PostMapping("/import")
    public R imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        // 方式1：(推荐) 通过 javabean的方式读取Excel内的对象，但是要求表头必须是英文，跟javabean的属性要对应起来
        //        List<User> list = reader.readAll(User.class);

        // 方式2：忽略表头的中文，直接读取表的内容
        List<List<Object>> list = reader.read(1);
        List<Dict> dicts = CollUtil.newArrayList();
        for (List<Object> row : list) {
            Dict dict = new Dict();
            dict.setName(row.get(0).toString());
            dict.setValue(row.get(1).toString());
            dict.setType(row.get(2).toString());
            dict.setType(row.get(3).toString());
            dict.setType(row.get(4).toString());
            dict.setType(row.get(5).toString());
            dicts.add(dict);
            System.out.println(dicts.toString());
        }
        dictService.saveBatch(dicts);
        return R.success(true);
    }


}
